from flask import Flask, make_response, request, session
import datetime
import os
app = Flask(__name__)
#  启用session
app.config['SECRET_KEY'] = os.urandom(24)  # 生成随机数种子，用于生成sessionId

@app.route("/")
def hello_world():
    return "flask我又来啦"

# 设置cookie
@app.route("/cookie")
def cookie():
    response = make_response("设置cookie成功")

    # response.set_cookie("name","dazhoulaoshi",max_age=10)
    expires_time = datetime.datetime.now() + datetime.timedelta(days=1)

    response.set_cookie("name", "dazhoulaoshi",expires=expires_time)
    response.set_cookie("sex", "nan",expires=expires_time)
    response.set_cookie("city", "beijing",expires=expires_time)

    return response

# 获取cookie
@app.route("/get_cookie")
def get_cookie():
    #  获取一个cookie
    name = request.cookies.get("name")
    print(name)
    # 一下获取所有
    cookies = request.cookies
    cookies_dict = request.cookies.to_dict()
    print(cookies)
    print(cookies_dict)
    for k,v in cookies_dict.items():
        print(k,v)
    return "获取cookie成功"

#  删除cookie
@app.route("/del_cookie")
def delete_cookie():
    response = make_response("删除cookie成功")
    # 删除一个cookie
    response.delete_cookie("name")

    # 删除所有cookie
    cookies_dict = request.cookies.to_dict()
    print(cookies_dict)
    for k, v in cookies_dict.items():
        print(k, v)
        response.delete_cookie(k)
    return response

#  操作session

# 添加session
@app.route("/add_session")
def add_session():
    # 设置session
    
    session['username'] = 'dazhoulaoshi'
    session['nickname'] = 'zhouge'
    session['role'] = 'admin'
    return 'session设置成功'

@app.route("/get_session")
def get_session():
    print(session)
    username = session.get("username")
    return "session获取成功" + username

@app.route("/del_session")
def delete_session():
    session.clear()
    return "session清除成功"


@app.route("/user/add")
def add_user():
    
    return "session设置成功"

@app.route("/user/update")
def update_user():
    session.update({'username': 'dazhoulaoshi', 'nickname': 'zhouge', 'role': 'admin'})
    return "session更新成功"

@app.route("/article/update")
def update_article():
    return ""


if __name__ == "__main__":
    app.run()
